package com.feng.gulimall.product.web;

import com.feng.gulimall.product.entity.CategoryEntity;
import com.feng.gulimall.product.service.CategoryService;
import com.feng.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;
    @GetMapping({"/", "/templates/index.html"})
    public String indexPage(Model model){
       List<CategoryEntity>categoryEntityList= categoryService.getLevel1Category();
       model.addAttribute("categorys",categoryEntityList);
        return "index";
    }
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public  Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map= categoryService.getCatalogJson();
        return map;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.获取一把锁 ，只要锁的名字一样就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2.加锁
        try {
            lock.lock();//阻塞式等待
            System.out.println("加锁成功，执行业务"+Thread.currentThread().getId());
            Thread.sleep(30000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println("释放锁...."+Thread.currentThread().getId());
        }
        return "hello";
    }
}
